package com.android.fragmentdemo.definervlayoutmanager;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CustomHorizontalLayoutManager extends RecyclerView.LayoutManager {

    private int mSumDx = 0;
    private int mTotalWidth = 0;

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        removeAllViews();
        detachAndScrapAttachedViews(recycler);
        int offsetX = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View child = recycler.getViewForPosition(i);
            //child.setRotationY(5);
            addView(child);
            measureChildWithMargins(child, 0, 0);
            int mWidth = getDecoratedMeasuredWidth(child);
            int mHeight = getDecoratedMeasuredHeight(child);
            //Log.d("dataItem111", "mWidth:" + child.getMeasuredWidth());
            //Log.d("dataItem111", "mHeight:" + child.getMeasuredHeight());
            layoutDecoratedWithMargins(child, offsetX, 0, offsetX + mWidth, mHeight);
            offsetX += mWidth;
        }
        //如果所有子view的宽度和没有填满RecyclerView,则将宽度设置为RecyclerView宽度
        mTotalWidth = Math.max(offsetX, getHorizontalSpace());
    }

    @Override
    public boolean canScrollHorizontally() {
        return true;
    }

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dx;
        if (mSumDx + dx < 0) {
            //滑动到左侧
            travel = -mSumDx;
        } else if (mSumDx + dx > mTotalWidth - getHorizontalSpace()) {
            //滑动到右侧
            travel = mTotalWidth - mSumDx - getHorizontalSpace();
        }
        mSumDx += travel;
        //平移容器中的item
        offsetChildrenHorizontal(-travel);
        return dx;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
       return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }

    private int getHorizontalSpace() {
        return getWidth() - getPaddingStart() - getPaddingEnd();
    }
}
